# Mathis Lohaus & Sören Stapel
# "Who commits to regional human rights treaties? 
#   Reputational benefits, sovereignty costs, and regional dynamics"
# Journal of Human Rights

# Questions re. this file: mathis.lohaus@fu-berlin.de 

# R version 4.0.2 (2020-06-22) -- "Taking Off Again"
# Platform: x86_64-w64-mingw32/x64 (64-bit)

library(tidyverse)
library(countrycode)
library(ggrepel)
library(ggtext)
library(ggalt)
library(patchwork)
library(viridis)
library(forcats)

setwd("C:/Users/Mathis Lohaus/Dropbox/R/regcom/regcom-stata/Journal submission/Replication files")
# Please set the working directory to the location of this script and the 2 .csv files



### ---- Replication file for Figures 1, 2, and 4 ------------------------------


# List of the 16 relevant treaty items:
treatylist <- c("au_1969", "au_1976", "au_1981", "au_1990", "au_1998", 
                "au_2003", "au_2006", "au_2008", "oas_1969",
                "oas_1969court", "oas_1985a",
                "oas_1988", "oas_1990", "oas_1994a", "oas_1994b",
                "oas_1999")

# Read data files:
ratif_dyad <- read.csv(file = "ratif_dyad.csv", na = ".")
ratifsums2 <- read.csv(file = "ratifcounts.csv", na = ".")


# ---- Figure 1: Cumulative ratifications---------------------------------------

# add a label for last data point for each treaty 
#     (that will appear on the right of the figure):
ratifsums2$name_lab <- 
  ifelse(ratifsums2$year == 2019, ratifsums2$treatylabel, NA)


# Plot the accumulated ratifications...

# This code uses the dummy variables to draw one type of line for normal treaties 
# ...and a second, bolder line for treaties defined as having high sov. costs



# OAS

gg1 <- ggplot(ratifsums2 %>% filter(audummy == 0), # filter the right RIO
              aes(x = year, y = ratifs_cum, group = treaty
              ))  +
  geom_line(data = ratifsums2 %>% 
              filter(audummy == 0 & costdummy == 0),
            size = 0.5) +
  geom_line(data = ratifsums2 %>% 
              filter(audummy == 0 &costdummy == 1),
            size = 1) +
  geom_segment(
    data = tibble(y = 0, x1 = 1969, x2 = 2020),
    aes(x = x1, xend = x2, y = y, yend = y),
    inherit.aes = FALSE,
    color = "gray",
    size = .8
  ) +
  scale_colour_manual(values = c("black", "#5d5d5d")) +
  geom_label_repel(aes(label = name_lab),
                   nudge_y = 1,
                   #nudge_x = 4,
                   xlim = c(2020.1, NA),
                   size = 3,
                   segment.size = 0.2,
                   segment.color = "dark gray") + 
  theme_minimal() +
  theme(legend.position = "none",
        panel.grid = element_blank()) +
  coord_cartesian(
    clip = "off",
    ylim = c(0, 35)
  ) +
  scale_x_continuous(
    expand = c(0, 0),
    limits = c(1969, 2035), 
    breaks = seq(1970, 2020, by = 10)
  ) +
  scale_y_continuous(
    expand = c(0, 0),
    breaks = seq(0, 35, by = 5)
  ) +
  labs(x = "", y = "Number of ratifications (OAS)")

gg1


# African Union

gg2 <- ggplot(ratifsums2 %>% filter(audummy == 1), # other RIO this time
              aes(x = year, y = ratifs_cum, group = treaty
              ))  +
  geom_line(data = ratifsums2 %>% 
              filter(audummy == 1 & costdummy == 0),
            size = 0.5) +
  geom_line(data = ratifsums2 %>% 
              filter(audummy == 1 & costdummy == 1),
            size = 1) +
  geom_segment(
    data = tibble(y = 0, x1 = 1969, x2 = 2020),
    aes(x = x1, xend = x2, y = y, yend = y),
    inherit.aes = FALSE,
    color = "gray",
    size = .8
  ) +
  scale_colour_manual(values = c("black", "#5d5d5d")) +
  geom_label_repel(aes(label = name_lab),
                   nudge_y = 1,
                   #nudge_x = 4,
                   xlim = c(2020.1, NA),
                   size = 3,
                   segment.size = 0.2,
                   segment.color = "dark gray") + 
  theme_minimal() +
  theme(legend.position = "none",
        panel.grid = element_blank()) +
  coord_cartesian(
    clip = "off",
    ylim = c(0, 55)
  ) +
  scale_x_continuous(
    expand = c(0, 0),
    limits = c(1969, 2035), 
    breaks = seq(1970, 2020, by = 10)
  ) +
  scale_y_continuous(
    expand = c(0, 0),
    breaks = seq(0, 55, by = 5)
  ) +
  labs(x = "", y = "Number of ratifications (OAU / AU)")


gg2 
# 900*500 px is a on-screen good size


# Combine both plots with patchwork:
ratifscombo <- gg1 / gg2

ratifscombo

# Printable figure:

ggsave("figure1.png", plot = ratifscombo,
       scale = 1, width = 30, height = 25, units = "cm",
       dpi = 300, limitsize = TRUE)


# ---- Figure 2: Average number of years until ratification --------------------

library(sf) # load additional packages for the world map
library(rnaturalearth) 
library(rnaturalearthdata) 
library(ggspatial) 
library(rgeos) 


# Let's alculate years until ratification for each country-treaty dyad

# Note the new "member" variable that tells us when states become eligible
#  (-> states cannot ratify unless they have joined the RIO first!)

# Also note that the ratif. variable itself is already in the correct format
#  (-> set to "NA" for years before treaties are available for ratification)

ratifspeed <- ratif_dyad %>%
  filter(treaty %in% treatylist) %>%
  group_by(treaty, country) %>%
  mutate(member = ifelse(year >= joinyear, 1, 0)) %>% #  create new variable
  transmute(id2 = id2,
            rio = rio,
            ccodealp = ccodealp,
            wdi_reg = wdi_reg,
            years = sum((ratif == 0 & member == 1), na.rm = T)) %>% 
                # ^ count years, keeping in mind states have to be eligible
  slice(1) %>%
  ungroup() %>%
  group_by(treaty) %>%
  ungroup() %>%
  arrange(treaty, years)


# Exclude states that were suspended
ratifspeed$years[ratifspeed$country == "Morocco"] <- NA
ratifspeed$years[ratifspeed$country == "South Sudan"] <- NA


# Calculate average speed by country (= what we will plot)
ratifspeed_avg <- ratifspeed %>%
  group_by(country) %>%
  transmute(ccodealp = ccodealp,
            rio = rio,
            wdi_reg = wdi_reg,
            years_avg = mean(years)) %>%
  slice(1) %>%
  ungroup()

# Look at the average speeds per RIO
ratifspeed %>% 
  filter(!is.na(years)) %>%
  group_by(rio) %>% 
  summarize(mean = mean(years))



# Now let's plot average ratification speed on a map

# Inspiration:
# https://www.r-spatial.org/r/2018/10/25/ggplot2-sf.html
# https://cran.r-project.org/web/packages/viridis/vignettes/intro-to-viridis.html


# ! remember to think about the limits (range) of the color scheme. 
#  -> What's the maximum average years for ratif. in each region?
#  OAS = 34 years; Caribbean = 29 years; AU = 23 years


#  So let's put the color range for all maps on the same scale:
maxyears <- 35


# Africa
map_au <- ne_countries(continent = c("africa"),
                       scale = "medium",
                       returnclass = "sf")



map_au$years_avg <- 0
map_au$years_avg <-
  ifelse(map_au$iso_a3 %in% ratifspeed_avg$ccodealp,
         ratifspeed_avg$years_avg[match(map_au$iso_a3, ratifspeed_avg$ccodealp)],
         NA)



ggau <- ggplot(data = map_au) +
  geom_sf(aes(fill = years_avg)) +
  scale_fill_viridis_c(option = "viridis", limits = c(0,maxyears)) +
  theme_minimal() + 
  labs(fill = "Mean number of years until ratification") +
  theme(legend.position="bottom",
        axis.text.x=element_blank(),
        axis.text.y=element_blank(),
        panel.grid = element_blank()) 

ggau


# Americas
map_oas <- ne_countries(continent = c("north america", "south america"),
                        scale = "medium",
                        returnclass = "sf")

map_oas <- map_oas %>%
  filter(iso_a3 %in% ratifspeed_avg$ccodealp)



map_oas$years_avg <- NA
map_oas$years_avg <- ratifspeed_avg$years_avg[match(map_oas$wb_a3, 
                                                    ratifspeed_avg$ccodealp)]

map_oas_crop <- st_crop(map_oas, xmin = -130, xmax = -30,
                        ymin = -60, ymax = 70)


ggoas <- ggplot(data = map_oas_crop) +
  geom_sf(aes(fill = years_avg)) +
  scale_fill_viridis_c(option = "viridis", limits = c(0,maxyears)) +
  #scale_fill_gradient(low = "dark green", high = "light gray", na.value = "white") +
  theme_minimal() + 
  theme(legend.position="none",
        axis.text.x=element_blank(),
        axis.text.y=element_blank(),
        panel.grid = element_blank())

ggoas

# Caribbean (to zoom in later)

map_carib <- map_oas %>%
  filter(subregion == "Caribbean")

ggcarib <- ggplot(data = map_carib) +
  geom_sf(aes(fill = years_avg)) +
  scale_fill_viridis_c(option = "viridis", limits = c(0,maxyears)) +
  # scale_fill_gradient(low = "dark green", high = "light gray", 
  #                     na.value = "white",
  #                     limits = c(0,36)) +
  theme_minimal() +
  theme(legend.position="none",
        axis.text.x=element_blank(),
        axis.text.y=element_blank(),
        panel.grid = element_blank(),
        plot.background=element_rect(fill = 'white', colour = 'black'))

ggcarib


# Combine OAS with Caribbean zoom plot / insert

ggoas2 <- ggoas +
  annotation_custom(
    grob = ggplotGrob(ggcarib),
    xmin = -80,
    xmax = -35,
    ymin = 10,
    ymax = 50
  )
ggoas2


# Combine OAS and OAU/AU
combomap <- (ggoas2 + ggau) / guide_area() + plot_layout(guides = "collect",
                                                         nrow = 2,
                                                         heights = c(9.5,0.5))

combomap


ggsave("figure2.png", plot = combomap,
       scale = 1, width = 25, height = 15, units = "cm",
       dpi = 300, limitsize = TRUE)


# --- Figure 3: Result of event history analysis -------------------------------

# Please see the Stata do-File!



# --- Figure 4: Treaties ratified before and after democratization episodes ----

# Create a new dataframe with country-year observations only for the years
#  belonging to democratization episodes

demcheck <- ratif_dyad %>%
  filter(treaty %in% treatylist) %>%
  filter(democratization3 == 1) %>%
  mutate(member = ifelse(year >= joinyear, 1, 0)) %>%
  filter(member == 1) %>%
  filter(!is.na(ratif)) %>%
  select(country, year, treaty, id2, rio, ratif)

# Summarize across all available treaties
demcheck2 <- demcheck %>%
  group_by(country, year) %>%
  summarize(ratifs = sum(ratif))

demcheck2$rio <- demcheck$rio[match(demcheck2$country, demcheck$country)]


# Manually change names for cases in which 1 country has multiple episodes
demcheck2$country <- 
  ifelse(demcheck2$country == "Burkina Faso" & demcheck2$year > 1980, 
         "Burkina Faso II", demcheck2$country)

demcheck2$country <- 
  ifelse(demcheck2$country == "Brazil" & demcheck2$year > 1976, 
         "Brazil II", demcheck2$country)

demcheck2$country <- 
  ifelse(demcheck2$country == "Ethiopia" & demcheck2$year > 1976, 
         "Ethiopia II", demcheck2$country)

demcheck2$country <- 
  ifelse(demcheck2$country == "Guinea-Bissau" & demcheck2$year > 1996, 
         "Guinea-Bissau II", demcheck2$country)

demcheck2$country <- 
  ifelse(demcheck2$country == "Guatemala" & demcheck2$year > 1987, 
         "Guatemala II", demcheck2$country)

demcheck2$country <- 
  ifelse(demcheck2$country == "Haiti" & demcheck2$year > 1992, 
         "Haiti II", demcheck2$country)

demcheck2$country <- 
  ifelse(demcheck2$country == "Haiti II" & demcheck2$year > 1996, 
         "Haiti III", demcheck2$country)

demcheck2$country <- 
  ifelse(demcheck2$country == "Mali" & demcheck2$year > 1994, 
         "Mali II", demcheck2$country)

demcheck2$country <- 
  ifelse(demcheck2$country == "Nicaragua" & demcheck2$year > 1981, 
         "Nicaragua II", demcheck2$country)

demcheck2$country <- 
  ifelse(demcheck2$country == "Niger" & demcheck2$year > 1994, 
         "Niger II", demcheck2$country)

demcheck2$country <- 
  ifelse(demcheck2$country == "Nigeria" & demcheck2$year > 1981, 
         "Nigeria II", demcheck2$country)

demcheck2$country <- 
  ifelse(demcheck2$country == "Peru" & demcheck2$year > 1982, 
         "Peru II", demcheck2$country)


# Condense data to one row per democratization episode
#  ...and determine the no. of ratifications in the first and last year
episodes <- demcheck2 %>%
  group_by(country) %>%
  transmute(rio = rio,
            start = min(year),
            end = max(year),
            rat1 = min(ratifs),
            rat2 = max(ratifs)) %>%
  slice(1)


# Now, we want to put the number of ratifications into context.
# --> Create a dataframe with the number of available treaties per RIO per year

yearlist <- seq(1969, 2019, by=1)

opentreaties_oas <- data.frame(yearlist,
                               total = c(2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
                                         3,4,5,
                                         4,4,
                                         5,5,5,5,
                                         7,7,7,7,7,
                                         8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8))



opentreaties_au <- data.frame(yearlist,
                              total = c(1,1,1,1,1,1,1,
                                        2,2,2,2,2,
                                        3,3,3,3,3,3,3,3,3,
                                        4,4,4,4,4,4,4,4,
                                        5,5,5,5,5,
                                        6,6,6,
                                        7,7,
                                        8,8,8,8,8,8,8,8,8,8,8,8))




# add number of potential ratifications (depending on the RIO!) to each episode

episodes$ratmin <- 0
episodes$ratmax <- NA

episodes$ratmax <- 
  ifelse(episodes$rio == "OAS", # select right reference list depending on RIO
         opentreaties_oas$total[match(episodes$end, opentreaties_oas$yearlist)],
         opentreaties_au$total[match(episodes$end, opentreaties_au$yearlist)])


# Now we just need to assign each episode a name to display in the figure
# -> Let's go with the start year and label (including II, III as necessary)
episodes$episode <- str_c(episodes$start, " ", episodes$country)


# Plot the OAS Episodes

gg <- ggplot(episodes %>% filter(rio == "OAS"))
gg <- gg + geom_segment(aes(y=fct_rev(episode), yend=fct_rev(episode), x=0, xend=ratmax), color="gray")

gg <- gg + geom_dumbbell(aes(x=rat1, xend=rat2, y=fct_rev(episode), group=episode),
                         size_x = 2, size_xend = 2, size = 1, colour = "black",
                         colour_x = "gray", colour_xend = "black")
gg <- gg + scale_x_continuous(breaks = seq(0, 9, by = 1))
gg <- gg + labs(y = "", x = "Ratifications (OAS)")

gg_oas <- gg + theme_classic()
gg_oas


# Plot the AU Episodes


gg <- ggplot(episodes %>% filter(rio == "AU"))
gg <- gg + geom_segment(aes(y=fct_rev(episode), yend=fct_rev(episode), x=0, xend=ratmax), color="gray")

gg <- gg + geom_dumbbell(aes(x=rat1, xend=rat2, y=fct_rev(episode), group=episode),
                         size_x = 2, size_xend = 2, size = 1, colour = "black",
                         colour_x = "gray", colour_xend = "black")
gg <- gg + scale_x_continuous(breaks = seq(0, 8, by = 1))
gg <- gg + labs(y = "", x = "Ratifications (OAU/AU)") 
gg_au <- gg + theme_classic()
gg_au


# Use patchwork to combine both into one figure
comboplot <- gg_oas + gg_au +
  plot_annotation(caption = "Gray lines indicate the range of potential ratifications, depending on how many treaties are available at the time.")

comboplot


ggsave("figure4.png", plot = comboplot,
       scale = 1, width = 22, height = 15, units = "cm",
       dpi = 300, limitsize = TRUE)


